package com.yanyeori.framework.datasource.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yanyeori.framework.core.context.UserContext;
import com.yanyeori.framework.core.entity.BaseEntity;
import com.yanyeori.framework.core.util.StringUtil;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 通用字段填充实现类
 *
 * @author chenkuan 2023/8/9
 */
public class CommonFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject != null && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();

            Date date = new Date();
            if (baseEntity.getCreateTime() == null) {
                baseEntity.setCreateTime(date);
            }
            if (baseEntity.getUpdateTime() == null) {
                baseEntity.setUpdateTime(date);
            }

            String username = StringUtil.defaultString(UserContext.username(), "");
            if (baseEntity.getCreateBy() == null) {
                baseEntity.setCreateBy(username);
            }
            if (baseEntity.getUpdateBy() == null) {
                baseEntity.setUpdateBy(username);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject != null && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();

            Date date = new Date();
            baseEntity.setUpdateTime(date);

            String username = StringUtil.defaultString(UserContext.username(), "");
            baseEntity.setUpdateBy(username);
        }
    }
}
